package pers.cz.orm.dao.processor;

import pers.cz.common.annotation.Column;
import utils.ObjUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: jef-orm
 * @description: 删除操作
 * @author: Cheng Zhi
 * @create: 2023-08-12 15:14
 **/
public class UpdateProcessor extends AbstractDbProcessor {

    @Override
    public DbProcessorEnums getOperEnum() {
        return DbProcessorEnums.UPDATE;
    }

    public String getSetParams() {

        StringBuilder sqlBuilder = new StringBuilder();
        Map<String, Object> entityInfo = new HashMap<>();
        // 反射执行get方法
        ObjUtils.getFieldNameAndValue(entity, entityInfo);
        Object[] objects = entityInfo.keySet().toArray();
        int commaCount = 0;
        for (int i=0; i<objects.length; i++) {
            commaCount ++;
            if (getIgnores().get(ObjUtils.under2camel((String) objects[i])) != null) {
                continue;
            }
            Column column = getColums().get(ObjUtils.under2camel((String) objects[i]));
            String columnName = column == null? (String) objects[i] : column.name();
            sqlBuilder.append(columnName);
            sqlBuilder.append(EQUALS);
            sqlBuilder.append(formatVal(entityInfo.get(objects[i])));

            if (commaCount != objects.length) {
                sqlBuilder.append(COMMA);
            }
        }

        return sqlBuilder.toString();
    }

    @Override
    public String bindSql() {

        // update test set a=1,b=2 where c=3;
        String key = getOperEnum().getKey();
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append(key);
        //sqlBuilder.append(getTableName());
        sqlBuilder.append(" set ");
        sqlBuilder.append(getSetParams());
        sqlBuilder.append(getWhereClause());
        sqlBuilder.insert(sqlBuilder.indexOf(SET), getTableName());
        return sqlBuilder.toString();
    }
}
